var crypto = require('crypto'),
    User = require('../models/user.js'),
    Post = require('../models/post.js');
var Comment = require('../models/comment.js');


module.exports = function(app){

  app.get('/',function(req,res){
    var pageNo = req.query.pn ? parseInt(req.query.pn) : 1,
        pageSize = req.query.ps ? parseInt(req.query.ps) : 10;
    Post.getTen(null,pageNo,pageSize,function(err,posts,total){
      if(err){
        posts = [];
      }
      res.render('index',{
        title:'主页',
        user: req.session.user,
        posts: posts,
        pageNo: pageNo,
        pageSize: pageSize,
        isFirstPage: (pageNo - 1) == 0,
        isLastPage: ((pageNo - 1)*pageSize + posts.length) == total,
        success: req.flash('success').toString(),
        error: req.flash('error').toString(),
        helpers: {
            count: function (num, inc) {
                    return num + inc;
            }
        }
      });
    });
  });

  app.get('/reg', checkNotLogin);
  app.get('/reg',function(req,res){
    res.render('reg', {
      title: '注册',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/reg', checkNotLogin);
  app.post('/reg',function(req,res){
    var name = req.body.name,
        password = req.body.password,
        password_re = req.body['password-repeat'];
    //校验用户输入的两次密码是否一致
    if(password_re != password) {
      req.flash('err', '两次输入的密码不一致');
      return res.redirect('/reg');//返回注册页
    }

    //生成密码的md5值
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    var newUser = new User({
      name: req.body.name,
      password: password,
      email: req.body.email
    });
    //检查用户名是否已经存在
    User.get(newUser.name, function (err, user) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      if (user) {
        req.flash('error', '用户已存在');
        return res.redirect('/reg');
      }
      //如果不存在就新增用户
      newUser.save(function (err, user) {
        if (err) {
          req.flash('error', err);
          return res.redirect('/reg');//注册失败返回注册页
        }
        console.log(req.session);
        req.session.user = user; //将用户信息存入session
        req.flash('success', '注册成功');
        res.redirect('/');
      });
    });
  });

  app.get('/login', checkNotLogin);
  app.get('/login',function(req,res){
    res.render('login', {
      title: '登陆',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/login', checkNotLogin);
  app.post('/login',function(req,res){
    var md5 = crypto.createHash('md5'),
        password = md5.update(req.body.password).digest('hex');
    //检查用户是否存在
    User.get(req.body.name,function(err,user){
      if(!user){
        req.flash('error','用户不存在！');
        return res.redirect('/login');  //用户不存在则跳转到登录页
      }
      //检查密码是否一致
      if(user.password != password){
        req.flash('error','密码错误！');
        return res.redirect('/login');
      }
      //用户名密码都匹配后，将用户信息存入session
      req.session.user = user;
      req.flash('success','登录成功！');
      res.redirect('/');
    })

  });

  app.get('/post', checkLogin);
  app.get('/post',function(req,res){
    res.render('post',{
      title:'发表',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.post('/post', checkLogin);
  app.post('/post',function(req,res){
    var currentUser = req.session.user,
        tags = [req.body.tag1, req.body.tag2, req.body.tag3],
        post = new Post(currentUser.name, currentUser.head, req.body.title, tags, req.body.post);
    post.save(function(err){
      if (err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      req.flash('success','发布成功！');
      res.redirect('/');
    })
  });

  app.get('/logout', checkLogin);
  app.get('/logout',function(req,res){
    req.session.user = null;
    req.flash('success','登出成功！');
    res.redirect('/');
  });

  //文件上传
  app.get('/upload',checkLogin);
  app.get('/upload',function(req,res) {
    res.render('upload', {
      title: '文件上传',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    })
  });

  app.post('/upload',checkLogin);
  app.post('/upload',function(req,res){
    req.flash('success','文件上传成功！');
    res.redirect('/upload');
  });

  app.get('/u/:name', function (req, res) {
    var pageNo = req.query.pn ? parseInt(req.query.pn) : 1,
        pageSize = req.query.ps ? parseInt(req.query.ps) : 10;
    User.get(req.params.name, function (err, user) {
      if (!user) {
        req.flash('error', '用户不存在');
        return res.redirect('/');
      }
      //查询并返回该用户的所有文章
      Post.getTen(user.name,pageNo,pageSize, function (err,posts,total) {
        if(err) {
          req.flash('error',err);
          res.redirect('/');
        }
        res.render('user', {
          title: user.name,
          posts: posts,
          pageNo: pageNo,
          pageSize: pageSize,
          isFirstPage: (pageNo - 1) == 0,
          isLastPage: ((pageNo - 1)*pageSize + posts.length) == total,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString(),
            helpers:{
                count: function (num, inc) {
                    return num + inc;
                }
            }
        });
      })
    });
  });

  app.get('/p/:_id', function (req,res) {
    Post.getOne(req.params._id, function (err,post) {
      if(err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      res.render('article', {
        title: post.title,
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString(),
        helpers: {
          equal: function (arg1, arg2, options) {
               if(arg1 == arg2){
                   //满足条件才继续执行，否则使用options.inverse(this)
                   return options.fn(this);
              }
          },
          reprintShow: function(options){
              var flag = true;
              if(req.session.user.name == post.name) {
                  flag = false;
              }
              if(req.session.user.name == post.reprint_info.reprint_from.name){
                  flag = false;
              }
              if (post.reprint_info.reprint_to){
                  post.reprint_info.reprint_to.forEach(function (reprint_to, index) {
                      if (reprint_to.name && req.session.user.name == reprint_to.name) {
                          flag = false;
                      }
                  });
              }else{
                  flag = false;
              }
              if(flag) {
                  return options.fn(this);
              }else{
                  return options.inverse(this);
              }
          }
        }
      });
    });
  });
    //兼容转载功能
    app.get('/u/:name/:day/:title', function (req,res) {
        Post.getOneOld(req.params.name,req.params.day,req.params.title, function (err,post) {
            if(err) {
                req.flash('error', err);
                return res.redirect('/');
            }
            res.render('article', {
                title: req.params.title,
                post: post,
                user: req.session.user,
                success: req.flash('success').toString(),
                error: req.flash('error').toString(),
                helpers: {
                    equal: function (arg1, arg2, options) {
                        if(arg1 == arg2){
                            //满足条件才继续执行，否则使用options.inverse(this)
                            return options.fn(this);
                        }
                    },
                    reprintShow: function(options){
                        var flag = true;
                        if(req.session.user.name == post.name) {
                            flag = false;
                        }
                        if(req.session.user.name == post.reprint_info.reprint_from.name){
                            flag = false;
                        }
                        if (post.reprint_info.reprint_to){
                            post.reprint_info.reprint_to.forEach(function (reprint_to, index) {
                                if (req.session.user.name == reprint_to.name) {
                                    flag = false;
                                }
                            });
                        }else{
                            flag = false;
                        }
                        if(flag) {
                            return options.fn(this);
                        }else{
                            return options.inverse(this);
                        }
                    }
                }
            });
        });
    });


  app.get('/edit/:_id', checkLogin);
  app.get('/edit/:_id', function (req,res) {
    var currentUser = req.session.user;
    Post.edit(req.params._id,currentUser.name, function (err,post) {
      if(err) {
        req.flash('error', err);
        return res.redirect('back');
      }
      res.render('edit', {
        title: '编辑',
        post: post,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    })
  })

  app.post('/edit/:_id',checkLogin);
  app.post('/edit/:_id',function(req,res) {
    var currentUser = req.session.user;
    Post.update(currentUser.name, req.params._id, req.body.post, function (err) {
      var url = encodeURI('/u/' + req.params._id);
      if(err) {
        req.flash('error', err);
        return res.redirect(url);//出错，返回文章页
      }
      req.flash('success','修改成功');
      res.redirect(url);//成功，返回文章页
    });


  });


  app.get('/remove/:name/:day/:title', checkLogin);
  app.get('/remove/:name/:day/:title', function (req, res) {
    var currentUser = req.session.user;
    Post.remove(currentUser.name, req.params.day, req.params.title, function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');
      }
      req.flash('success', '删除成功!');
      res.redirect('/');
    });
  });

  app.post('/u/:name/:day/:title', function (req, res) {
    var date = new Date(),
        time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
    var md5 = crypto.createHash('md5'),
        email_MD5 = md5.update(req.body.email.toLowerCase()).digest('hex'),
        head = "http://www.gravatar.com/avatar/" + email_MD5 + "?s=48";
    var comment = {
      name: req.body.name,
      head: head,
      email: req.body.email,
      website: req.body.website,
      time: time,
      content: req.body.content
    };
    var newComment = new Comment(req.params.name, req.params.day, req.params.title, comment);
    newComment.save(function (err) {
      if (err) {
        req.flash('error', err);
        return res.redirect('back');
      }
      req.flash('success', '留言成功!');
      res.redirect('back');
    });
  });

  app.get('/archive', function (req,res) {
    Post.getArchive(function (err,posts) {
      if(err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      res.render('archive',{
        title: '存档',
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString(),
        helpers: {
          showYear: function(index, options) {
              if ((index == 0) || (posts[index].time.year != posts[index - 1].time.year)) {
                  return options.fn(this);
              }
          }
        }
      });
    });
  });


  app.get('/tags', function (req, res) {
    Post.getTags(function (err, posts) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      res.render('tags', {
        title: '标签',
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });


  app.get('/tags/:tag', function (req, res) {
    Post.getTag(req.params.tag, function (err, posts) {
      if (err) {
        req.flash('error',err);
        return res.redirect('/');
      }
      res.render('tag', {
        title: 'TAG:' + req.params.tag,
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  app.get('/search', function (req, res) {
    Post.search(req.query.keyword, function (err, posts) {
      if (err) {
        req.flash('error', err);
        return res.redirect('/');
      }
      res.render('search', {
        title: "SEARCH:" + req.query.keyword,
        posts: posts,
        user: req.session.user,
        success: req.flash('success').toString(),
        error: req.flash('error').toString()
      });
    });
  });

  app.get('/links', function (req, res) {
    res.render('links', {
      title: '友情链接',
      user: req.session.user,
      success: req.flash('success').toString(),
      error: req.flash('error').toString()
    });
  });

  app.get('/reprint/:name/:day/:title/:_id', checkLogin);
  app.get('/reprint/:name/:day/:title/:_id', function (req, res) {
    Post.edit(req.params._id, req.params.name, function (err, post) {
      if (err) {
        req.flash('error', err);
        return res.redirect(back);
      }
      var currentUser = req.session.user,
          reprint_from = {name: post.name, day: post.time.day, title: post.title},
          reprint_to = {name: currentUser.name, head: currentUser.head};
      Post.reprint(reprint_from, reprint_to, function (err) {
        if (err) {
          req.flash('error', "转载失败!");
          return res.redirect('back');
        }
        req.flash('success', '转载成功!');
        var url = encodeURI('/u/' + post.name + '/' + post.time.day + '/' + post.title);
        //跳转到转载后的文章页面
        res.redirect(url);
      });
    });
  });




  //一定要放在所有的请求的最后边
  app.use(function (req, res) {
    res.render("404", {
        layout: false
    });
  });

  function checkLogin(req,res,next){
    if(!req.session.user){
      req.flash('error','未登录！');
      res.redirect('/login');
    }
    next();// 转移控制权
  }

  function checkNotLogin(req,res,next){
    if(req.session.user){
      req.flash('error','已登录！');
      res.redirect('back');//返回之前的页面
    }
    next();// 转移控制权
  }

};

































